import { CSSProperties, FC, memo, ReactElement, useEffect, useRef, useState } from "react";
import { debounce } from 'lodash'
import * as echarts from 'echarts'

interface IProps {
  option: echarts.EChartsOption
  width?: string
  height?: string
  children?: ReactElement
  theme?: string
  resizeDelay?: number
}

const Echarts: FC<IProps> = memo((props) => {
  const wrapperRef = useRef<HTMLDivElement | null>(null)
  const echartsIns = useRef<echarts.ECharts>()

  const [styles] = useState<CSSProperties>({
    width: `${props.width || '100%'}`,
    height: `${props.height || '100%'}`
  })

  const initEcharts = () => {
    echartsIns.current = echarts.init(wrapperRef.current, props.theme || 'light')
    echartsIns.current?.setOption(props.option)
  }

  const echartsResize = debounce(() => {
    echartsIns.current?.resize()
  }, props.resizeDelay || 300)

  useEffect(() => {
    echartsIns.current?.setOption(props.option)
  }, [props.option])

  useEffect(() => {
    initEcharts()

    window.addEventListener('resize', echartsResize, false)
    return () => {
      window.removeEventListener('resize', echartsResize, false)
      echartsIns.current?.dispose()
    }
  }, [])

  return (
    <div style={{ ...styles }} ref={wrapperRef}></div>
  )
})

export default Echarts